﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using HtmlAgilityPack;

namespace OrderAggregator.InputFormats.Holiday
{
    /// <summary>
    /// Парсер заявок от Холидей
    /// </summary>
    public class HolidayFormat : BaseOrderFormat
    {
        public readonly static HolidayFormat Instance = new HolidayFormat();

        private HolidayFormat()
        {
        }
       
        /// <summary>
        /// Parse
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="getStream"></param>
        /// <returns></returns>
        public override BaseOrder Parse(string filePath, Func<System.IO.Stream> getStream)
        {
            if (!string.Equals(System.IO.Path.GetExtension(filePath), dotHTML, StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }


            string content;
            using (var reader = new StreamReader(getStream(), Encoding.Default))
            {
                content = reader.ReadToEnd();
            }
            content = content.Replace("</br>", string.Empty);
            
            var doc = new HtmlDocument();
            doc.LoadHtml(content);
            
            var docNode = doc.DocumentNode;

            var body = docNode.Descendants("body").FirstOrDefault();
            var table = body.Element("table");

            var rowTags = table.Elements("tr").ToArray();

            if (rowTags.Length <= 1)
            {
                return null;
            }

            var order = new BaseOrder();

            var divTags = body.Elements("div").ToArray();

            //Id, ReceiveTime
            {
                string orderId;
                DateTime receiveTime;
                ParseNumberAndDate(divTags[0].InnerText, out orderId, out receiveTime);
                
                order.Id = orderId;

                order.ReceiveTime = ParseDate(divTags[2].InnerText);
            }

            order.Client = divTags[1].InnerText;

            for (int i = 1; i < rowTags.Length; i++)
            {
                var tr = rowTags[i];

                var orderRow = new BaseOrderRow();

                var tdTags = tr.Elements("td").ToArray();

                orderRow.ProductCode = tdTags[1].InnerText;
                orderRow.ProductName = tdTags[2].InnerText;
                orderRow.Count = decimal.Parse(tdTags[3].InnerText, System.Globalization.CultureInfo.InvariantCulture);

                order.OrderRows.Add(orderRow);
            }

            return order;
        }

        private static void ParseNumberAndDate(
            string numberAndDate,
            out string number,
            out DateTime date
            )
        {
            number = "";
            date = DateTime.MinValue;

            var numberSeparatorPos = numberAndDate.IndexOf(" от ");

            if (numberSeparatorPos < 0)
            {
                return;
            }

            var numberPos = numberAndDate.IndexOf("№");

            number = numberAndDate.Substring(numberPos + 1, numberSeparatorPos - numberPos - 1);

            string dateStr = numberAndDate.Substring(numberSeparatorPos + 4);
            date = DateTime.Parse(dateStr, RuCulture);

            if (string.IsNullOrEmpty(numberAndDate))
            {
                return;
            }
        }

        private static DateTime ParseDate(string dateField)
        {
            var sepPos = dateField.IndexOf(':');

            if (sepPos < 0)
            {
                throw new Exception("Ошибка в формате заявки");
            }

            var dateStr = dateField.Substring(sepPos + 1);
            return DateTime.Parse(dateStr, RuCulture);
        }
    }
}
